package com.shire.shire_interface.filter;

import com.shire.shire_interface.common.utils.StrUtils;
import com.shire.shire_interface.common.utils.WxReqUtils;
import com.shire.shire_interface.conf.InstanceManager;
import com.shire.shire_interface.constants.WxErrorCode;
import com.shire.shire_interface.model.WxReqInfo;
import com.shire.shire_interface.model.account.DeviceInfo;
import com.shire.shire_interface.model.account.DeviceKey;
import com.shire.shire_interface.model.account.WxStation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WxFilter implements Filter {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String ip = getIp(request);
        // 判断访问来源
//		if(!ip.startsWith("192.168")){
//			response.getWriter().print("{\"success\":false, \"msg\":\"ip is lost\", \"code\":"+ WxErrorCode.SYS_ERROR+"}");
//			response.getWriter().flush();
//			return;
//		}
        String uri = request.getRequestURI().substring(1);
        String k = request.getHeader("k");
//        String k1 = request.getHeader("k1");
        if (StrUtils.isBlank(k)) {
            k = request.getParameter("k");
        }
//        if (StrUtils.isBlank(k1)) {
//            k1 = request.getParameter("k1");
//        }
        if (StrUtils.isBlank(k) || k.length() < 32) {
            response.getWriter().print("{\"success\":false, \"msg\":\"k is lost\", \"code\":" + WxErrorCode.LOST_K + "}");
            response.getWriter().flush();
            return;
        }

//        if (StrUtils.isBlank(k1) || k1.length() != 8) {
//            response.getWriter().print("{\"success\":false, \"msg\":\"k1 is lost\", \"code\":" + WxErrorCode.LOST_K1 + "}");
//            response.getWriter().flush();
//            return;
//        }

        String n = request.getHeader("n");
        if (StrUtils.isBlank(n)) {
            n = request.getParameter("n");
        }
        if (StrUtils.isBlank(n) && !uri.endsWith("fetchCmd.wx")) {
            response.getWriter().print("{\"success\":false, \"msg\":\"n is lost\", \"code\":" + WxErrorCode.LOST_N + "}");
            response.getWriter().flush();
            return;
        }

//        logger.info("[" + ip + "]Req: url=" + request.getRequestURL() + ", query=" + request.getQueryString() + ", k=" + k + " k1=" + k1);
        request.setAttribute("k", k);
        request.setAttribute("n", n);
//        request.setAttribute("k1", k1);
        DeviceInfo deviceInfo = null;
        WxStation wxStation = null;
        DeviceKey deviceKey = null;
        try {

            deviceInfo = InstanceManager.getInstance().getDeviceInfoService().getDeviceInfoByUuid(k);
            if (deviceInfo == null) {
                logger.warn("设备不存在[k=" + k + "]！！");
                sendResponse(response, "{\"success\":false, \"msg\":\"device is not exists.\", \"code\":" + WxErrorCode.UNREG_DEVICE + "}");
                return;
            }



//            deviceKey = InstanceManager.getInstance().getDeviceKeyService().selectByKey(k1);
//            if (deviceKey == null) {
//                logger.warn("App KEY 不存在[uri=" + uri + "][k=" + k + ", n=" + n + ", k1 = "+ k1 + " ]！！");
//                sendResponse(response, "{\"success\":false, \"msg\":\"station[" + n + "] is not exists.\", \"code\":" + WxErrorCode.UNREG_STATION + "}");
//                return;
//            }

//            if (deviceKey.getStatus() != 0 || (new Date()).getTime() > deviceKey.getExpiredate().getTime()) {
//                logger.warn("App KEY无效 在[uri=" + uri + "][k=" + k + ", n=" + n + ", k1 = "+ k1 + " ]！！");
//                sendResponse(response, "{\"success\":false, \"msg\":\"station[" + n + "] is not exists.\", \"code\":" + WxErrorCode.UNREG_STATION + "}");
//                return;
//            }

            wxStation = InstanceManager.getInstance().getStationService().getStationByNK(n, k);
//            if (wxStation != null) {
//                logger.warn("App位置信息不存在[uri=" + uri + "][k=" + k + ", n=" + n + "]！！");
//                sendResponse(response, "{\"success\":false, \"msg\":\"station[" + n + "] is not exists.\", \"code\":" + WxErrorCode.UNREG_STATION + "}");
//                return;


//                if (deviceKey.getRealudid() == null || !deviceKey.getRealudid().equals(wxStation.getRealudid())) {
//                    deviceKey.setRealudid(wxStation.getRealudid());
//                    InstanceManager.getInstance().getDeviceKeyService().updateDeviceKey(deviceKey);
//                }
//            }


//                if(!uri.endsWith("reqAccount.wx") && !uri.endsWith("reportApp.wx")){ // 判断账号是否存在
//                    String wxAccount = wxStation.getWxaccount();
//                    if(StrUtils.isBlank(wxAccount)){
//                        logger.warn("App位置信息未配置账号[uri="+uri+"][k="+k+", n="+n+"]！！");
//                        sendResponse(response, "{\"success\":false, \"msg\":\"WxAccount for station["+n+"] is not exists.\", \"code\":"+WxErrorCode.UNSET_ACCOUNT_FOR_STATION+"}");
//                        return;
//                    }
//                }
//            }
        } catch (Exception e) {
            logger.error("查询设备信息异常[k=" + k + "]：", e);
            sendResponse(response, "{\"success\":false, \"msg\":\"Get Device Exception.\", \"code\":-1}");
            return;
        }

        WxReqUtils.setContain(new WxReqInfo(request, response, deviceInfo, wxStation));
        filterChain.doFilter(request, response);
    }

    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        return ip == null ? request.getRemoteAddr() : ip;
    }

    @Override
    public void destroy() {

    }

    private void sendResponse(HttpServletResponse response, String msg) throws IOException {
        response.getWriter().print(msg);
        response.getWriter().flush();
        return;
    }


}
